/**
 * @method：replaceAll
 * @createdBy：HuangJian
 * @date：2018/11/1
 * @description：字符串替换函数
 *
 */
// eslint-disable-next-line no-extend-native
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
  if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
    return this.replace(new RegExp(reallyDo, ignoreCase ? 'gi' : 'g'), replaceWith)
  } else {
    return this.replace(reallyDo, replaceWith)
  }
}

/**
 * @method：typeOf
 * @params：
 * @description：获取变量类型
 */
export function typeOf(obj) {
  const toString = Object.prototype.toString
  const str = toString.call(obj)
  const regExp = /\[object (\w*)\]/
  if (regExp.test(str)) {
    return (RegExp.$1 || '').toLowerCase()
  }
}

/**
   * @method：copyObjProps
   * @param：
   *  val：要拷贝的对象
   *  props:需要的拷贝的属性，类型为数组
   *  mode:是否深拷贝子对象,默认值为true
   * @returns：新对象的应用
   * @description：用于拷贝对象特定属性
   *  var props=['id','accntName'],val={id:'WA1111',accntName:'XX信息',acctLevel:'VIP'};
   *  var newVal=copyObjProps(val,props);
   *  newVal的值为:{id:'WA1111',accntName:'XX信息'}
   */
export function copyObjProps(val, props, mode = true) {
  if (typeOf(val) !== 'object' || ['array', 'string'].indexOf(typeOf(props)) < 0) {
    return {}
  }
  const newVal = {}
  if (typeOf(props) === 'string') props = [props]
  for (const i in props) {
    const key = props[i]
    const prop = val[key]
    const type = typeOf(prop)
    const ifDeepCopy = mode && ['array', 'object'].indexOf(type) > -1
    newVal[key] = ifDeepCopy ? deepClone(prop) : prop
  }
  return newVal
}

export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/* eslint-disable no-loop-func */
export function isMultiText(result) {
  return (
    result.type !== 'select' &&
        // result.type !== 'picklist' &&
        result.type !== 'date' &&
        result.type !== 'datetime' &&
        result.type !== 'number' &&
        result.condition !== 'between'
  )
}
export function isNoValue(result) {
  if (typeof result !== 'object') return
  return result.condition === 'IS NULL' || result.condition === 'NOT NULL'
}

function copyItem(item = {}) {
  var newItem = {}
  for (var key in item) {
    const prop = item[key]
    if (key === 'pickProps') {
      const keys = ['showKey', 'mainField', 'reverseMap', 'pickMap']
      newItem[key] = copyObjProps(prop, keys)
    } else {
      newItem[key] = prop
    }
  }
  return newItem
}
export function getResults(results) {
  var newResults = [];
  (results || []).forEach((result) => {
    newResults.push(copyItem(result))
  })
  return newResults
}
function getMap(item) {
  const props = item.pickProps
  var map = props.pickMap
  if (props.reverseMap) {
    var newMap = {}
    for (var k in map) {
      newMap[map[k]] = k
    }
    map = newMap
  }
  return map
}
function getRelatedField(item) {
  var result = item.relateField
  if (!result) {
    var map = getMap(item) || {}
    if (map.hasOwnProperty('id') && map.id) {
      result = map.id
    }
  }
  return result
}
/**
 * @method：makeFiltersRaw
 * @createdBy:HuangJian
 * @date:2019/1/16
 * @params：
 * filters:字段配置信息
 * results：字段筛选条件
 * @description：用于生成filtersRaw
 */
export function makeFiltersRaw(filters, results) {
  var rslt = []
  results = getResults(results) || []
  filters = filters || []

  /* 单字段筛选条件*/
  filters.forEach((filter) => {
    var arr = []
    results.forEach((result) => {
      if (!result.multi && result.field === filter.field) {
        arr.push(result)
      }
    })
    for (var i = 0; i < arr.length; i++) {
      var tmp = arr[i]
      if (tmp.multival) {
        if (isMultiText(tmp)) {
          var strRaw = tmp.value
          strRaw = strRaw.replaceAll('，', ',')
          var tmpArr = strRaw.split(',') || []
          var newValues = []
          tmpArr.forEach((obj) => {
            if (obj) newValues.push(obj)
          })
          tmp.values = newValues
        }
        // if (tmp.type === 'picklist') {
        //   // eslint-disable-next-line no-redeclare
        //   var newValues = []
        //   var key = tmp.isLink ? tmp.pickProps.showKey : tmp.pickProps.mainField
        //   const relateField = getRelatedField(tmp)
        //   if (relateField) {
        //     tmp.field = relateField
        //     key = 'id'
        //   }
        //   (tmp.values || []).forEach((val) => newValues.push(val[key] || val[relateField] || ''))
        //   tmp.values = newValues
        // }
      } 
      // else if (tmp.type === 'picklist') {
      //   // eslint-disable-next-line no-redeclare
      //   var key = tmp.isLink ? tmp.pickProps.showKey : tmp.pickProps.mainField
      //   const relateField = getRelatedField(tmp)
      //   if (relateField) {
      //     tmp.field = relateField
      //     key = 'id'
      //   }
      //   const val = tmp.pickval || {}
      //   tmp.value = val[key] || val[relateField] || ''
      // }

      var obj = {
        id: tmp.field + (i > 0 ? String(i) : ''),
        property: tmp.field,
        operator: tmp.condition,
        value: tmp.multival ? '[' + tmp.values + ']' : tmp.value
      }
      if (isNoValue(tmp)) {
        obj.value = ''
        rslt.push(obj)
        continue
      }
      
      if (['date','datetime'].includes(tmp.type)) {
        obj.type = tmp.type
        if (tmp.type==='date' && (tmp.condition === '>' ||  tmp.condition === '>=')) {
          obj.value += ' 00:00:00'
        }
        if (tmp.type==='date' && (tmp.condition === '<' || tmp.condition === '<=')) {
          obj.value += ' 23:59:59'
        }
        if (tmp.condition === 'between' && tmp.values.length > 1) {
          obj.value =tmp.type==='date'? tmp.values[0] + ' 00:00:00' : tmp.values[0]
          obj.operator = '>='
          arr.push({
            multi: false,
            type: tmp.type,
            condition: '<=',
            field: tmp.field,
            value: tmp.values[1],
            values: []
          })
        }
        /* if (tmp.condition === 'today') {
          // 查询当天日期数据处理
          // rslt.push(obj)
          const lastValue = `${obj.value} 23:59:59`
          obj.value += ' 00:00:00'
          obj.operator = '>='
          arr.push({
            multi: false,
            type: tmp.type,
            condition: '<=',
            field: tmp.field,
            value: lastValue,
            values: []
          })
        } */
      }

      if (tmp.type === 'number' && tmp.condition === 'between') {
        obj.operator = '>='
        obj.value = tmp.start
        arr.push({
          multi: false,
          type: 'number',
          condition: '<=',
          field: tmp.field,
          value: tmp.end,
          values: []
        })
      }
      
      rslt.push(obj)
    }
  })

  /* 多字段筛选条件*/
  results.forEach((result) => {
    if (result.multi) {
      if (
        result.field &&
                Array.isArray(result.field) &&
                result.field.length) {
        var obj = {
          id: '',
          property: '[' + result.field + ']',
          operator: result.condition,
          value: result.value
        }
        for (var i = 0; i < result.field.length; i++) {
          obj.id += result.field[i]
          obj.id += i < result.field.length - 1 ? '-' : ''
        }
        rslt.push(obj)
      }
    }
  })
  return rslt
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  if (!time) return ''
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if (time.indexOf('T')) {
        time = time.replace('T', ' ')
      }
      if (time.indexOf('Z')) {
        time = time.replace('Z', ' ')
      }
      if (/^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else {
        time = time.replace(/-/g, '/') // 处理safari与ie兼容
      }
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}